package com.dance.spring.learn.proxy;

import com.dance.spring.learn.proxy.impl.UserDaoImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class JDKProxy {

    public static void main(String[] args) {

        Class<?>[] classes = {UserDao.class};
        UserDaoImpl userDao = new UserDaoImpl();
        UserDao userDao1 = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), classes, new UserDaoProxy(userDao));
        int add = userDao1.add(1, 2);
        System.out.println(add);

    }

}

class UserDaoProxy implements InvocationHandler{

    private UserDao userDao;

    public UserDaoProxy(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("方法之前执行:"+method.getName()+",参数:"+ Arrays.toString(args));
        // 执行方法
        Object invoke = method.invoke(userDao, args);
        System.out.println("方法之后执行:返回值为:"+invoke);
        return invoke;
    }
}
